package com.wasp.collector.service.akka;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wasp.collector.content.Content;
import com.wasp.collector.data.BaseModel;
import com.wasp.collector.data.RequestContext;
import com.wasp.collector.service.chain.AbstractHandleChain;

import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.japi.Creator;

public class SaverActor extends UntypedActor {
	private static final Logger log = LoggerFactory.getLogger(SaverActor.class);

	RequestContext requestContext;
	Content content;
	List<? extends BaseModel> handledData;
	public SaverActor(Content content,
			List<? extends BaseModel> handledData) {
		this.requestContext = content.getRequestContext();
		this.content = content;
		this.handledData = handledData;
	 }

	public static Props props(Content content,
			List<? extends BaseModel> handledData) {
		return Props.create(new newCreator(content,
				handledData));
	}

	static class newCreator implements Creator<SaverActor> {

		private static final long serialVersionUID = -1772539428749702579L;
		List<? extends BaseModel> handledData;
		Content content;
		public newCreator(Content content,
				List<? extends BaseModel> handledData) {
			super();
			this.content = content;
			this.handledData = handledData;
		}

		@Override
		public SaverActor create() throws Exception {
			return new SaverActor(content,handledData);
		}
	}


	@Override
	public void onReceive(Object msg) throws InterruptedException {
		ActorResult result = new ActorResult();
		result.setExecTime(new Date());
		try {
			if(msg instanceof AbstractHandleChain){
				AbstractHandleChain handleChain = (AbstractHandleChain)msg;
				AbstractHandleChain tmp = handleChain;
				while(tmp != null){
					tmp.setContent(content).setNeedHandleData(handledData);
					tmp = tmp.getSuccessor();
				}
				handleChain.handleRequest();
			}
			
		} catch (Exception ex) {
			log.error("",ex);
			result.setException(ex);
			
		} finally {
			stopSelf();
		}
	}
	private void stopSelf(){
		getContext().stop(self());
	}
}
